#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //read
#include <sys/types.h>  //open
#include <sys/stat.h>
#include <fcntl.h>
#include <utmp.h>   //utmp
#include <time.h>   //strftime

int main()
{
    struct utmp record;
    int fd;
    int len = sizeof(record);
    struct tm *p;
    time_t t;
    char fortime[40];
    if ( (fd = open(UTMP_FILE, O_RDONLY)) == -1 )
    {
        perror( UTMP_FILE );    
        exit(1);
    }
    while(read(fd,&record,len))
    {
        if(record.ut_type == USER_PROCESS)//只显示类型为USER_PROCESS的一般进程
        {
            printf("%-10.10s",record.ut_user);
            printf("%-10.10s",record.ut_line);
            //以下为对时间的转换操作
            t = record.ut_time;     
            p = localtime(&t);
            strftime(fortime,40,"%F %R",p);
            printf("%12s",fortime);

            if(record.ut_host[0]!='\0');
                printf("\t(%s)",record.ut_host);
            printf("\n");
        }
    }
    
    if (close(fd) == -1)
    {
        perror( UTMP_FILE );    
        exit(1);
    }
    return 0;
}
